function setupXEWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) {
        callback(WebViewJavascriptBridge)
    } else {
        console.log("WebViewJavascriptBridge is required by SDK");
        document.addEventListener(
            'WebViewJavascriptBridgeReady', function () {
                callback(WebViewJavascriptBridge)
            }, false);
    }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0)
}

function executeNative(methodName, params, { success, fail, complete }) {
    console.log('调用了-->', methodName)
    setupXEWebViewJavascriptBridge(function (bridge) {
      console.log(bridge, methodName)
        bridge.callHandler(methodName, params, (resString) => {
            let res = JSON.parse(resString)
            console.log('回调结果-->', methodName, params, res)
            if (res.code === 0) {
                success && success(res)
            } else {
                fail && fail(res)
            }
            complete && complete(res)
        });
    });
}

function registerJs(methodName, { success, complete, info }) {
    setupXEWebViewJavascriptBridge(function (bridge) {
        console.log('监听的桥-->1', bridge, complete)
        bridge.registerHandler(methodName, (data, responseCallback) => {
            console.log('监听的桥-->2', data)
            let res = data
            success && success(res)
            complete && complete(res)
            responseCallback(JSON.stringify(info))
        });
    });
}
/**
 * 苹果代币支付
 * @param success
 * @param fail
 */
const callAppPay = function ({payParams,success,fail}) {
    executeNative('callAppPay', JSON.stringify({payParams}), {success,fail})
}
/**
 * 调起原生弹窗方法
 * @param success
 * @param fail
 */
const nativeIAPRechargeByAlert = function ({payParams,success,fail}) {
  executeNative('nativeIAPRechargeByAlert', JSON.stringify({payParams}), {success,fail})
}

/**
 * 跳充值页面方法
 * @param success
 * @param fail
 */
 const nativeIAPRecharge = function ({payParams,success,fail}) {
    executeNative('nativeIAPRecharge', JSON.stringify({payParams}), {success,fail})
  }

/**
 * 监听充值是否完成
 * @param success
 */
 const noticeOrderH5Refresh =  function ({ success, fail }) {
    registerJs('noticeOrderH5Refresh', { success })
}



window.wx = {
  ...window.wx,
  callAppPay,
  nativeIAPRechargeByAlert,
  noticeOrderH5Refresh,
  nativeIAPRecharge
};
